package controller

import (
	"context"
	"time"

	v1 "mygf2/api/v1"
	"mygf2/library"

	"github.com/gogf/gf/v2/frame/g"
)

var (
	User = CUser{}
)

type CUser struct{}

func (c *CUser) Login(ctx context.Context, req *v1.LoginReq) (res *v1.Res, err error) {
	//解析数据 req
	//请求中控登录
	zkurl, err := g.Cfg().Get(ctx, "ThirdPartyServices.zkUrl")
	if err != nil {
		panic(err)
	}
	var zkRes v1.ThirdServiceRes
	g.Client().PostVar(ctx, zkurl.String()+"auth/login", g.Map{
		"username": req.Username,
		"password": req.Password,
	}).Scan(&zkRes)
	if zkRes.Code != nil && *(zkRes.Code) == 0 {
		library.GlobalCache.Set(ctx, zkRes.Data.AccessToken, zkRes.Data.Userinfo, time.Duration(zkRes.Data.ExpiresIn)*time.Second)
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    0,
			"message": "登录成功",
			"data":    zkRes.Data,
		})
	} else {
		g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
			"code":    -1,
			"message": zkRes.Message,
			"data":    zkRes.Data,
		})
	}
	return
}
func (c *CUser) GetUserInfo(ctx context.Context, req *v1.UserinfoReq) (res *v1.ThirdServiceUserDataRes, err error) {
	userInfo := ctx.Value("user-info")
	token := ctx.Value("token")
	library.GlobalCache.Set(ctx, token, userInfo, 86400*time.Second)
	g.RequestFromCtx(ctx).Response.WriteJsonExit(userInfo)
	return
}
func (c *CUser) Logout(ctx context.Context, req *v1.LogoutReq) (res *v1.Res, err error) {
	token := ctx.Value("token")
	//调用一次远程登出
	zkurl, err := g.Cfg().Get(ctx, "ThirdPartyServices.zkUrl")
	if err != nil {
		panic(err)
	}
	_, err = g.Client().SetHeader("Authorization", g.RequestFromCtx(ctx).GetHeader("Authorization")).Post(ctx, zkurl.String()+"auth/logout", g.Map{
	})
	if err != nil {
		panic(err)
	}
	_ , err = library.GlobalCache.Remove(ctx, token)
	if err != nil {
		panic(err)
	}
	g.RequestFromCtx(ctx).Response.WriteJsonExit(g.Map{
		"code":    0,
		"message": "登出成功",
		"data":    "",
	})
	
	return
}
